<script>
import EchartBase from './base/echartBase'

export default {
  extends: EchartBase,
  data() {
    return {
      title: '',
      xAxisData: [],
      yAxisData: [],
      legendData: []
    }
  },
  methods: {
    handleDataSource(obj) {
      if (!obj) return

      this.title = obj.title || ''
      this.xAxisData = obj.xAxisData || []
      this.yAxisData = obj.yAxisData || []

      this.$nextTick(() => {
        if (this.chart) {
          this.chartOption = this.initChartOption()
          this.chart.setOption(this.chartOption)
        }
      })
    },
    initChartOption() {
      const option = {
        title: this.initTitle(),
        grid: this.initGrid(),
        xAxis: this.initXAxis(),
        yAxis: this.initYAxis(),
        toolbox: this.dataSource.showToolbox ? this.initToolbox() : {},
        tooltip: this.initTooltip(),
        series: this.initSeries(),
        legend: {
          type: 'scroll',
          data: this.legendData,
          top: 28
        },
      }
      if (this.dataSource.color && this.dataSource.color.length === this.yAxisData.length) {
        option.color = this.dataSource.color
      }
      return option
    },
    initXAxis() {
      const xAxis = {
        type: 'category',
        boundaryGap: this.dataSource.boundaryGap !== undefined ? this.dataSource.boundaryGap : true,
        data: this.xAxisData,
      }
      return xAxis
    },
    initYAxis() {
      const yAxis = {
        type: 'value'
      }
      return yAxis
    },
    initSeries() {
      // https://echarts.apache.org/zh/option.html#series-line
      var series = []
      var tmp = []
      for (let i = 0; i < this.yAxisData.length; i++) {
        const yAxisData = this.yAxisData[i]
        const serie = {
          type: 'line',
          name: yAxisData.name || '',
          symbol: 'emptyCircle',
          showSymbol: yAxisData.showSymbol !== undefined ? yAxisData.showSymbol : true,
          stack: yAxisData.stack || '',
          lineStyle: {
            width: yAxisData.lineWidth !== undefined ? yAxisData.lineWidth : 1
          },
          areaStyle: yAxisData.areaStyle || null,
          emphasis: {
            focus: 'series'
          },
          smooth: yAxisData.smooth || false,
          data: yAxisData.data,
          animationDuration: this.animationDuration
        }
        if (i === this.yAxisData.length - 1) {
          serie.label ={
            show: true,
            position: 'top'
          }
        }
        series.push(serie)
        tmp.push(yAxisData.name)
      }
      this.legendData = tmp.length > 1 ? tmp : []
      return series
    }
  }
}
</script>